import socket
import threading

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

server_address = ('', 9999)  # 将空字符串绑定到所有可用的网络接口
server_socket.bind(server_address)
roomnumber = ''
clients = []
judge = []

server_socket.listen(2)
print('Server is listening on {}:{}'.format(*server_address))


def handle_client(client_socket, client_address):
    while True:
        try:
            # 接收客户端发送的数据
            data = client_socket.recv(1024).decode('utf-8')
            response = data_processing(data)
            # 转发消息给其他客户端
            if response:
                for client in clients:
                    if client != client_socket:
                        client.send(response.encode('utf-8'))
                        print("已转发", response)
            if response == 'same':
                client_socket.send(response.encode('utf-8'))
            elif response == 'win':
                client_socket.send("failure".encode('utf-8'))
            elif response == 'failure':
                client_socket.send("win".encode('utf-8'))
        except socket.error as e:
            # 客户端断开连接
            clients.remove(client_socket)
            client_socket.close()
            break


def data_processing(data):
    response1 = ''
    if "roomnumber=" in data:
        print('接收到了房间号:', data[11:])
        response1 = "1 ready"
    elif "joinroom=" in data:
        response1 = "2 ready"
    elif data == "start":
        response1 = "start"
    elif data == '5' or data == '2' or data == '0':
        if judge:
            print(judge)
            if judge[0] == data:
                response1 = 'same'
            elif ((data == '5' and judge[0] == '0')or
                  (data == '2' and judge[0] == '5')or
                  (data == '0' and judge[0] == '2')):
                response1 = 'failure'
            else:
                response1 = 'win'
            judge.pop()
        else:
            judge.append(data)
    elif data == "dapao" or data == "fanghuzhao" or ("attack=" in data):
        response1 = data
    return response1


while True:
    print('等待连接中')
    # 等待客户端连接
    client_socket, client_address = server_socket.accept()
    print('已连接到 {}:{}'.format(*client_address))
    clients.append(client_socket)
    client_thread = threading.Thread(target=handle_client, args=(client_socket, client_address))
    client_thread.start()

